package com.cac.demo.controller.inStoreroom;

import com.cac.demo.dao.gkLog.MsGkLogDao;
import com.cac.demo.dao.outStoreRoom.OutStoreroomDao;
import com.cac.demo.service.MsSslShelves.MsSslShelvesService;
import com.cac.demo.util.CreateCommonLog;
import com.cac.demo.util.GkLogTaskCreateUtil;
import com.cac.demo.util.WcsLogRecord;
import com.cac.demo.util.adapter.ResponseMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/inStoreroom")
@Slf4j
public class InStoreroomRest {
    @Autowired
    private MsSslShelvesService msSslShelvesService;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Autowired
    private MsGkLogDao msGkLogDao;
    @Autowired
    private OutStoreroomDao outStoreroomDao;
    @Autowired
    private WcsLogRecord wcsLogRecord;
    @Autowired
    private GkLogTaskCreateUtil gkLogTaskCreateUtil;

    /*物料入库——缓存箱回库*/
    @Transactional
    @PostMapping("/inStoreroomQuery")
    public ResponseMsg<String> inStoreroomQuery(@RequestBody HashMap map){
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        //从前端接收IP，在叫箱表中匹配该IP下剩余箱子
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String operationBit = null;
        String boxType = "WORKBIN";
        //获取操作编码
        operationBit = msSslShelvesService.findStartCode(IP,boxType);
        //判断该物料是否为大件物料
        if (map.get("workbinCode").equals("312080030000")) {
            return responseMsg.setRetCode("200").setMessage("大件货物不回箱，请进行人工处理！");
        }else {
            //yebo 2023-06-09 新增，调用wcs处理当前托盘/箱子未完成任务
            wcsLogRecord.dealWmsUnFinishTask((String)map.get("workbinCode"));
            if (map.get("workbinCode") != null && !"".equals(map.get("workbinCode"))) {
                try {
                    HashMap in = new HashMap();
                    in.put("palletCode", map.get("workbinCode"));
                    in.put("command", "5");
                    in.put("boxType", "WORKBIN");
                    in.put("startCode", operationBit);
                    //调用创建回库日志
                    String s = createCommonLog.inBound(in);
                    if(s!="200"){
                        return responseMsg.setMessage(s).setRetCode("201");
                    }
                    HashMap outFirst = new HashMap();
                    //获取操作编码
                    operationBit = msSslShelvesService.findStartCode(IP, boxType);
                    outFirst.put("endCode", "xyssj" + operationBit);
                    outFirst.put("func", "receive");
                    outFirst.put("palletCode", map.get("workbinCode"));
                    //调用流量控制
                    HashMap callRtrun = createCommonLog.callWCSInterface(outFirst);
                    String str = (String) callRtrun.get("retCode");
                    if (str.equals("200")) {
                        outStoreroomDao.updateMsGkLogIsBack(map);
                        return responseMsg.setRetCode("200").setMessage((String) callRtrun.get("msg"));
                    } else return responseMsg.setRetCode("201").setMessage((String) callRtrun.get("msg"));

                } catch (Exception e) {
                    e.printStackTrace();
                    return responseMsg.setRetCode("201").setMessage("回库失败");
                }
            } else {
                responseMsg.setRetCode("201");
                responseMsg.setMessage("无法下达回库命令！");
                return responseMsg;
            }
        }
    }
    /*零件、成品退货——缓存箱回库*/
    @Transactional
    @PostMapping("/partInStoreroom")
    public ResponseMsg<String> partInStoreroom(@RequestBody HashMap map){
        ResponseMsg<String> responseMsg = new ResponseMsg<>();
        //获取IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String operationBit = null;
        String boxType = "WORKBIN";
        //获取操作编码
        operationBit = msSslShelvesService.findStartCode(IP,boxType);
        try {
            List<String> hashmap = (List<String>) map.get("workbinCode");
            if(hashmap.size()==0){
                responseMsg.setRetCode("201").setMessage("缓存箱回库失败！");
            }
            for(int i =0;i<hashmap.size();i++){
                String workbinCode = hashmap.get(i);
                HashMap in = new HashMap();
                in.put("palletCode", workbinCode);
                in.put("command", "5");
                in.put("boxType", "WORKBIN");
                in.put("startCode", operationBit);
                //调用创建回库日志
                String s = createCommonLog.inBound(in);
                if(s!="200"){
                    return responseMsg.setMessage(s).setRetCode("201");
                }
                HashMap outFirst = new HashMap();
                //获取操作编码
                operationBit = msSslShelvesService.findStartCode(IP, boxType);
                outFirst.put("endCode", "xyssj" + operationBit);
                outFirst.put("func", "receive");
                outFirst.put("palletCode", workbinCode);
                //调用流量控制
                HashMap callRtrun = createCommonLog.callWCSInterface(outFirst);
                String str = (String) callRtrun.get("retCode");
                if (str.equals("200")) {
                    return responseMsg.setRetCode("200").setMessage((String) callRtrun.get("msg"));
                } else return responseMsg.setRetCode("201").setMessage((String) callRtrun.get("msg"));
            }

        } catch (Exception e){
            e.printStackTrace();
            return responseMsg.setRetCode("201");
        }
        return responseMsg;
    }
    /*分拣管理、工艺更改缓存箱回库*/
    @Transactional
    @PostMapping("/sortStoreRoomIn")
    public ResponseMsg<HashMap> sortStoreRoomIn(@RequestBody HashMap map){
        ResponseMsg<HashMap> responseMsg = new ResponseMsg<>();
        String workbinCode= (String) map.get("workbinCode");
        if(("").equals(workbinCode)){
             responseMsg.setRetCode("201").setMessage("无法下达缓存箱回库命令！");
        }
        //获取IP
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        //判断是否为大件，大件直接改状态
        if("312080030000".equals(workbinCode)){
            msGkLogDao.updateBigWorkbin(IP);
            return responseMsg.setRetCode("200").setMessage("大件箱子回库成功");
        }

        /**
         * 判断下一个缓存箱是否位当前缓存箱
         * **/
        List<HashMap> gkLogs = msGkLogDao.queryRepeatWorkbin(map);
        if(gkLogs.size()>1){
            log.info("相同操作盘");
            for(int i=0;i<gkLogs.size();i++){
                if(i==0){
                    msGkLogDao.updateWorkbinFinish(gkLogs.get(i));
                    log.info("updateWorkbinFinish============执行============"+map.toString());
                }else{
                    msGkLogDao.updateWorkbinOper(gkLogs.get(i));
                    log.info("updateWorkbinOper============执行============"+map.toString());
                }
            }
            return responseMsg.setRetCode("201").setMessage("当前缓存箱不需要回库,请继续扫该缓存箱操作");
        }

        /**
         * yebo 2023-07-12
         * 判断当前回库的缓存箱的对应的工作包待执行的任务是否小于等于2，如果是则创建下一个工作包任务
         * */
        gkLogTaskCreateUtil.createNextPackageTask(IP);

        String operationBit = null;
        String boxType = "WORKBIN";
        //获取操作码
        operationBit = msSslShelvesService.findStartCode(IP,boxType);
        try {
            HashMap in = new HashMap();
            in.put("palletCode",map.get("workbinCode"));
            in.put("command","5");
            in.put("boxType", "WORKBIN");
            in.put("startCode",operationBit);
            //创建日志
            String s = createCommonLog.inBound(in);
            if(s!="200"){
                return responseMsg.setMessage(s).setRetCode("201");
            }
            //调用流程控制逻辑
            HashMap outFirst = new HashMap();
            outFirst.put("endCode","xyssj"+operationBit);
            outFirst.put("func","sort");
            outFirst.put("boxType", "WORKBIN");
            outFirst.put("palletCode",map.get("workbinCode"));
            outFirst.put("backTask","backWorkBin");
            //调用流量控制
            HashMap callRtrun = createCommonLog.callWCSInterface(outFirst);
            String str = (String) callRtrun.get("retCode");
            if(str.equals("200")){
                 responseMsg.setRetCode("200");
                 responseMsg.setResponseBody(callRtrun);
            }
            else  {
                responseMsg.setRetCode("201").setMessage((String) callRtrun.get("msg"));
            }
            return responseMsg;
        } catch (Exception e){
            e.printStackTrace();
            return responseMsg.setRetCode("201").setMessage("回库失败");
        }
    }
}
